package com.hulk.dryad.persistence.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.CacheConstants;
import com.hulk.dryad.common.constant.enums.YNFlag;
import com.hulk.dryad.persistence.entity.DictCode;
import com.hulk.dryad.persistence.entity.DictType;
import com.hulk.dryad.persistence.entity.enums.DictTypeEnum;
import com.hulk.dryad.persistence.mapper.DictCodeMapper;
import com.hulk.dryad.persistence.mapper.DictTypeMapper;
import com.hulk.dryad.persistence.service.DictTypeService;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hulk
 * @since 2019-05-16
 */

@Service
public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, DictType> implements DictTypeService {


	@Setter
   private  DictCodeMapper dictCodeMapper ;



	@Override
	public DictType getByType(String dictType){
		if (StringUtils.isBlank(dictType)){
			return null;
		}
		DictType type = new DictType();
		type.setDictType(dictType);
		type.setUseFlag(YNFlag.Y.getCode());
		return this.getOne(new QueryWrapper(dictType));
	}

	/**
	 * 根据ID 删除字典
	 * @param id 字典ID
	 * @return
	 */
	@Override
	@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public R removeDictType(Integer id) {
		DictType dict = this.getById(id);
		// 系统内置
		if (DictTypeEnum.SYSTEM.getType().equals(dict.getRsv1())) {
			return R.failed("系统内置字典不能删除");
		}
		baseMapper.deleteById(id);
		dictCodeMapper.delete(Wrappers.<DictCode>lambdaQuery().eq(DictCode::getDictType, dict.getDictType()));
		return R.ok();
	}

	/**
	 * 更新字典
	 * @param dict 字典
	 * @return
	 */
	@Override
	public R updateDictType(DictType dict) {
		DictType sysDict = this.getById(dict.getId());
		// 系统内置
		if (DictTypeEnum.SYSTEM.getType().equals(sysDict.getRsv1())) {
			return R.failed("系统内置字典不能修改");
		}
		return R.ok(this.updateById(dict));
	}
}
